package devlog

import (
	"context"
	"time"

	"device-admin/config/mysql"
	"device-admin/internal/models"

	sharding "192.168.1.75/go-pkg/db-sharding"
	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

// AddDevEventLog 新增
func AddDevEventLog(robotID, msg string, level int) {
	db := mysql.NewDB()
	dbs := sharding.GetDB(context.Background(), db, models.DevEventLogTpl{}, time.Now().Unix(), time.Now().Unix())
	dbs.WriteDB.Create(&models.DevEventLog{
		RobotID: robotID,
		Msg:     msg,
		Level:   level,
	})
}

// DevEventLogList 列表
func DevEventLogList(robotID string, startTime, endTime int64, level, page, limit int) (eventLog []models.DevEventLog, total int64) {
	// 查询近3天的数据
	dbs := sharding.GetDB(context.Background(), mysql.NewDB(), models.DevEventLogTpl{}, startTime, endTime)
	tx := dbs.QueryDB
	// 设备id
	if robotID != "" {
		tx = tx.Where("robot_id = ?", robotID)
	}
	// 时间区间
	if startTime > 0 && endTime > 0 && startTime <= endTime {
		tx = tx.Where("created_at BETWEEN ? AND ?", startTime, endTime)
	}
	// 日志等级
	if level >= 0 {
		tx = tx.Where("level = ?", level)
	}
	// 共享查询条件
	tx1 := tx.Session(&gorm.Session{})
	// 总数
	tx1.Count(&total)
	// 查询分页数据
	helper.Gorm{}.Paginate(tx, page, limit)
	tx.Order("created_at desc").
		Find(&eventLog)
	return
}
